package onlinejudge.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 路径拦截器,没登录时只可以浏览problem/list、solution/list、community/list、user/otherspace
 * 若浏览到其他页面就返回首页登录
 * @author tpw
 *
 */
public class PathInterceptor implements HandlerInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Object currentUser=request.getSession().getAttribute("currentUser");
		if(currentUser==null) {
			String[] urls=request.getRequestURL().toString().split("/");
			String requestUrl=urls[urls.length-2]+"/"+urls[urls.length-1];
			if(requestUrl.equals("problem/list")||requestUrl.equals("solution/list")||requestUrl.equals("community/list")||requestUrl.equals("user/otherspace")||requestUrl.equals("user/login")||requestUrl.equals("user/register")) {
				return true;
			}
			request.getSession().setAttribute("unLogin", true);
			response.sendRedirect("/onlinejudge/problem/list?pager.offset=0");
			return false;
		}
		request.getSession().removeAttribute("unLogin");
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
